package model.semantics;

import model.State;
import model.VariableTable;

public class ForNode extends Node<Integer> {
    Node<Integer> mySetup;
    Node<Integer> myCondition;
    Node<Integer> myStep;
    Node<Integer> myBody;

    public ForNode(Node<Integer> setup, Node<Integer> condition,
            Node<Integer> step, Node<Integer> body) {
        mySetup = setup;
        myCondition = condition;
        myStep = step;
        myBody = body;
    }

    @Override
    public Integer evaluate(State<Integer> state) {
        // Construct inner variable table to evaluate for loop in.
        VariableTable<Integer> outerTable = state.getVariableTable();
        VariableTable<Integer> innerTable = outerTable.clone();

        state.setVariableTable(innerTable);

        mySetup.evaluate(state);

        int out = 0;
        while (myCondition.evaluate(state) > 0) {
            out = myBody.evaluate(state);
            myStep.evaluate(state);
        }

        state.setVariableTable(outerTable);

        return out;
    }

}
